package com.haiertvbic.tvnow;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.haiertvbic.tvnow.model.LocalCodeBean;
import com.haiertvbic.tvnow.model.ProgramBean;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.protocol.CAEProtocol;
import com.haiertvbic.tvnow.service.ServiceUtil;
import com.haiertvbic.tvnow.service.SwitchChanellCallback;
import com.haiertvbic.tvnow.util.AppManager;
import com.haiertvbic.tvnow.util.LocateToast;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.SetActivityView;

/**
 * 节目在其他频道的播放情况，需要上一屏传入节目标识
 * 
 * @author sun
 * 
 */
public class TVNOWProgramStateAcitivity extends Activity {
	private Activity context = TVNOWProgramStateAcitivity.this;
	private static final String TAG = "ThreeAcitivity";
	protected static final int GET_PROSTATION_FAIL = 03;
	protected static final int GET_PROSTATION_SUC = 04;
	private static final int GET_LOCAL_CODE_FAIL = 05;

	private TextView pro_name;
	private ListView pro_cha_list;
	private ProgressBar bar_on_cha;
	private LinearLayout anim3;
	private View view;

	private String proId;
	private String proName;
	private ArrayList<ProgramBean> programList;
	private int currentCha = -200;
	private int switchCha = -200;
	private boolean canSwitch;

	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {

			case GET_PROSTATION_FAIL:
				// 获取频道数据失败，消失加载数据进度条
				bar_on_cha.setVisibility(View.GONE);
				LocateToast.locateToast(
						context,
						200,
						getResources().getString(
								R.string.get_pro_failed_try_again));
				break;
			case GET_PROSTATION_SUC:
				// 获取数据成功，适配显示数据，消失加载数据的进度条
				bar_on_cha.setVisibility(View.GONE);
				if (programList!=null&&programList.size()>0) {
					pro_cha_list.setAdapter(new ProChaAdapter());
					canSwitch = true;
				}
				break;
			case GET_LOCAL_CODE_FAIL:
				// 获取地域码失败
				LocateToast.locateToast(context, 200,
						getResources()
								.getString(R.string.get_local_code_failed));
				break;
			case 0:
				LocateToast.locateToast(
						context,
						200,
						getResources().getString(
								R.string.read_change_msg_failed));
				break;

			case 4004500:
				LocateToast.locateToast(context, 200,
						getResources().getString(R.string.change_success));
				currentCha = switchCha;
				try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;

			case 4004501:
				LocateToast
						.locateToast(
								context,
								200,
								getResources().getString(
										R.string.channel_non_existent));
				break;

			case 4004502:
				LocateToast.locateToast(context, 200,
						getResources().getString(R.string.please_connect_crb));
				break;

			case 4004503:
				LocateToast.locateToast(context, 200,
						getResources().getString(R.string.no_set_crb));
				break;

			case -2002:
				LocateToast.locateToast(context, 200,
						getResources().getString(R.string.connect_break_off));
				break;

			default:
				break;
			}
		}

	};

	/**
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_program_state_tvnowontv);
		view = SetActivityView.setActivityView(getWindow(), getWindowManager());
		AppManager.activityList.add(this);

		Intent intent = getIntent();
		proId = intent.getStringExtra("PRO_ID");
		String s = intent.getStringExtra("PRO_NAME");
		s = s.replaceAll("[0-9]", "");
		proName = s;
		SLog.v(TAG, "获取的PROID----》" + proId + "-----PRO_NAME" + proName);
		initView();
		Animation inAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_in_right);
		anim3.setAnimation(inAnimation);
		anim3.startAnimation(inAnimation);
		getResultPre();
	}

	/**
	 * 初始化界面控件
	 */
	private void initView() {
		anim3 = (LinearLayout) findViewById(R.id.anim3_ll);
		pro_name = (TextView) findViewById(R.id.pro_name);
		pro_name.setText(proName);
		pro_cha_list = (ListView) findViewById(R.id.pro_cha_list);
		bar_on_cha = (ProgressBar) findViewById(R.id.bar_on_cha);
		pro_cha_list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int chanId = programList.get(arg2).getCid();
				if (canSwitch && currentCha != chanId) {
					ServiceUtil.changeChannel(context, chanId,
							new SwitchChanellCallback() {
								@Override
								public void returnData(int source,
										int resultCode, int result) {
									myHandler.sendEmptyMessage(resultCode);
								}
							});
					switchCha = chanId;
				}

				// ProduceThread.seconds = 60;
			}

		});
		pro_cha_list.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// ProduceThread.seconds = 60;

			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}

		});
	}

	// }

	/**
	 * 填充的adapter，节目在其他频道播放的情况
	 * 
	 * @author sun
	 */
	public class ProChaAdapter extends BaseAdapter {

		public int getCount() {
			return programList.size();
		}

		public Object getItem(int position) {
			return programList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null)
				convertView = LayoutInflater.from(context).inflate(
						R.layout.layout_program_state_tvnowontv_item, null);
			TextView chaName = (TextView) convertView
					.findViewById(R.id.cha_name);
			TextView proName = (TextView) convertView
					.findViewById(R.id.pro_name);
			TextView staTime = (TextView) convertView
					.findViewById(R.id.start_time);
			TextView tomorrow = (TextView) convertView
					.findViewById(R.id.state_tomorrow_tvnow);
			
			Calendar c = Calendar.getInstance();
			int week = c.getTime().getDay();
			if (week == 0) {
				week = 7;
			}
			ProgramBean p = programList.get(position);
			if (p != null) {
				chaName.setText(p.getCname());
				proName.setText(p.getPn());
				String s = p.getPstime() + "c";
				s = s.replace(":00c", "");
				if (p.getPweekday() == (week + 1)) {
					tomorrow.setText(context.getResources().getString(
							R.string.tomorrow));
					tomorrow.setVisibility(View.VISIBLE);
					staTime.setText(s);
				} else {
					tomorrow.setVisibility(View.GONE);
					staTime.setText(s);
				}
			}
			return convertView;
		}
	}

	/**
	 * 得倒节目在其他台播放的数据
	 */
	public void getResultPre() {
		new Thread() {
			public void run() {
				bar_on_cha.setVisibility(View.VISIBLE);
				LocalCodeBean loc_cod_bean = CAEProtocol.getLocalCode();
				if (loc_cod_bean == null) {
					myHandler.sendEmptyMessage(GET_LOCAL_CODE_FAIL);
				} else {
					if (loc_cod_bean.getReturn_code() == 4006301) {
						myHandler.sendEmptyMessage(GET_LOCAL_CODE_FAIL);
					} else {
						programList = EPGWeb.getSituation(context, proId,
								loc_cod_bean.getCity() + "");
						if (programList != null) {
							myHandler.sendEmptyMessage(GET_PROSTATION_SUC);
						} else {
							myHandler.sendEmptyMessage(GET_PROSTATION_FAIL);
						}
					}
				}
			};
		}.start();

	}

	/**
	 * 按下按键时的反应
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// ProduceThread.seconds = 60;
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			Intent intent = new Intent();
			intent.setClass(context, TVNOWProgramListActivity.class);
			finish();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			// ProduceThread.canRun = false;
			// ProduceThread.exit = false;
			// IsExit.isExit(this);
		}
		return super.onKeyDown(keyCode, event);
	}
}
